import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/entity/lz_text.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/good/entity/shop_order4app_show_entity.dart';
import 'package:shopping_group/modle/main/bloc/details_validate_bloc.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/person/bloc/my_address_bloc.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/modle/person/ui/add_adress_page.dart';
import 'package:shopping_group/modle/person/ui/my_adress_page.dart';
import 'package:shopping_group/modle/play/ui/fugou_runing_paly_page.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/color_util.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../play/ui/details_runing_paly_page.dart';

class DetailsToPalyPage extends StatefulWidget {
  final CommoSpec4AppRecordEntity entity;

  DetailsToPalyPage({Key key, this.entity}) : super(key: key);

  @override
  _DetailsToPalyPageState createState() => _DetailsToPalyPageState();
}

class _DetailsToPalyPageState extends State<DetailsToPalyPage> {
  MyAddressBloc _addressBloc;
  List<SouJianRenEntity> _listEntity = [];
  StreamSubscription _selectSubscription;
  StreamSubscription _addSubscription;
  StreamSubscription _validateSubscription;

  StreamSubscription _calculSubscription;

  // StreamSubscription _zfbSubscription;
  DetailsValidateBloc _bloc;
  // DetailsRuningPlayBloc _playBloc;
  // StreamSubscription _zfbStartListSubscription;
  // StreamSubscription _zfbCallblackListSubscription;
  // StreamSubscription _zfbCompleteListSubscription;
  // bool isToZfbPlayView = false;
  String _count = '1';
  String _outPrice = '0';
  @override
  void initState() {
    super.initState();
    _addressBloc = MyAddressBloc();
    _bloc = DetailsValidateBloc();
    _addressBloc.initDate.add(null);
    _outPrice = this.widget.entity.outPrice;
    // _playBloc = DetailsRuningPlayBloc();
    _selectSubscription = eventBus.on<SelectOSouJianRenEvent>().listen((event) {
      List<SouJianRenEntity> temp = [];
      temp.add(event.entity);
      temp.addAll(_listEntity);
      _listEntity = temp;
      _addressBloc.initDate.add(_listEntity);
    });

    _addSubscription = eventBus.on<AddSouJianRenEvent>().listen((event) {
      BaseConstant.adressEntity = event.entity;
      _listEntity.add(event.entity);
      _addressBloc.initDate.add(_listEntity);
    });
    _reloadPrice();

    ///如果是订单详情过来的
    _orderDetail();
    // _zfbCompleteListSubscription =
    //     eventBus.on<ZfbCompeteEvent>().listen((event) {
    //   BotToast.closeAllLoading();
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   String openType = this.widget.entity.openType;
    //   String orderId = this.widget.entity.orderId;
    //   if (openType == 'order') {
    //     eventBus.fire(RefreshOrderEvent(orderId));
    //     RouteUtil.closeView();
    //   } else if ('fuGood' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
    //   } else if ('fuGoodjuan' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.FUGOU_VIEW_PAGE);
    //   } else if ('dfk' == openType) {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.DFK_VIEW_PAGE);
    //   } else {
    //    RouteUtil.popUntil(PageConstance.MAIN_PAGE);
    //     RouteUtil.goView(PageConstance.ALL_ORDER_PAGE);
    //   }
    // });

    // _zfbCallblackListSubscription =
    //     eventBus.on<ZfbCallbackEvent>().listen((event) {
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   Map<String, dynamic> data = {};
    //   data['val'] = event.id;
    //   data['selectId'] = this.widget.entity.selectId;
    //   _playBloc.zfbPlayCompeteDate.add(data);
    // });

    // _zfbStartListSubscription = eventBus.on<ZfbStartEvent>().listen((event) {
    //   if (isToZfbPlayView) {
    //     return;
    //   }
    //   Map<String, dynamic> data = event.parm.toJson();
    //   data['type'] = BaseConstant.SHOP_TYPE;
    //   _playBloc.zfbPlayDate.add(data);
    // });

    // _zfbSubscription = eventBus.on<ZfbShopEvent>().listen((event) {
    //   Map<String, dynamic> data = {};
    //   data['userId'] = BaseConstant.userId;
    //   data['shopOrderId'] = this.widget.entity.orderId;
    //   data['commoSpecId'] = this.widget.entity.id;
    //   data['shopCt'] = '1';
    //   data['getGoodInfoId'] = BaseConstant.adressEntity.id;
    //   data['payVal'] = this.widget.entity.outPrice;
    //   data['payOption'] = 'PO_ZI_FU_BAO';
    //   data['openType'] = this.widget.entity.openType;
    //   data['orderId'] = this.widget.entity.orderId;
    //   data['custGroupsRelaId'] = this.widget.entity.custGroupsRelaId;
    //   data['selectId'] = '';
    //   isToZfbPlayView = false;
    //   _playBloc.playDate.add(data);
    // });

    _validateSubscription = eventBus.on<ValidateNewShopEvent>().listen((event) {
      // isToZfbPlayView = true;
      this.widget.entity.valEntity = event.entity;
      this.widget.entity.count = _count;
      if ('Y' == this.widget.entity.isReBuy) {
        RouteUtil.goParameter(FuGouRuningPalyPage(entity: this.widget.entity));
      } else {
        RouteUtil.goParameter(
            DetailsRuningPalyPage(entity: this.widget.entity));
      }
    });
  }

  _reloadPrice() {
    Map<String, dynamic> data = {};
    Map<String, dynamic> entityJson = this.widget.entity.toJson();

    data['userId'] = BaseConstant.userId;
    data['commoSpecId'] = this.widget.entity.id;
    data["lstCommoOpts"] = entityJson["lstCommoOpts"];
    data['shopCt'] = _count;
    HttpUtilAll.post(Apis.CALCUL_SHOP_ORDER_PRICE, data: data, headers: {},
        success: (result) {
      BotToast.closeAllLoading();
      if (null != result) {
        // this.widget.entity.outPrice = result["val"];
        _outPrice = result["val"];
        setState(() {});
      }
    }, error: (errorMsg) {
      BotToast.closeAllLoading();
      // 请求失败返回的错误信息
      BotToast.showText(text: errorMsg);
    });
  }

  //如果是订单传过来的, 要去请求一下订单详情

  _orderDetail() {
    if (widget.entity.orderId == null) return;
    if (widget.entity.orderId.length == 0) return;

    Map<String, dynamic> data = {};

    data['val'] = widget.entity.orderId;

    HttpUtilAll.post(Apis.ORDER_DETAILS_URL, data: data, headers: {},
        success: (result) {
      BotToast.closeAllLoading();

      if (null != result) {
        CommoSpec4AppRecordEntity recordEntity =
            CommoSpec4AppRecordEntity.fromJson(result);
        widget.entity.lstCommoOptsModels = recordEntity.lstCommoOptsModels;
        _count = recordEntity.shopCt;
        _reloadPrice();
      }
    }, error: (errorMsg) {
      BotToast.closeAllLoading();
      // 请求失败返回的错误信息
      BotToast.showText(text: errorMsg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '确认订单'),
      body: Container(
        height: double.infinity,
        color: Colours.gray_f0,
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _showAddressView(),
              SizedBox(height: 8),
              _shoppingView(),
              SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.symmetric(vertical: 8),
                decoration: BoxDecoration(
                  color: Colours.title_white,
                ),
                child: Row(
                  children: <Widget>[
                    SizedBox(
                      width: 16,
                    ),
                    Expanded(
                      child: WidgetUtils.getTextColorView(
                          '购买数量', Colours.text_2222, Dimens.FONT_SIZE_16),
                    ),
                    GestureDetector(
                      onTap: () {
                        if ('1' == _count) {
                          return;
                        }
                        _count = (int.parse(_count) - 1).toString();
                        _reloadPrice();
                        // Map<String, dynamic> data = {};
                        // data['userId'] = BaseConstant.userId;
                        // data['commoSpecId'] = this.widget.entity.id;
                        // data['realPrice'] = this.widget.entity.outPrice;
                        // data['shopCt'] = _count;
                        // _bloc.validateDate.add(data);
                        // setState(() {

                        //   _count = (int.parse(_count) - 1).toString();
                        //   _outPrice = (double.parse(this.widget.entity.outPrice) * int.parse(_count)).toString();
                        // });
                      },
                      child: Icon(
                        Icons.remove_circle,
                        color: Colours.themeColor,
                        size: 24,
                      ),
                    ),
                    SizedBox(
                      width: 2,
                    ),
                    WidgetUtils.getTextColorView(
                        _count, Colours.text_2222, Dimens.FONT_SIZE_16),
                    SizedBox(
                      width: 2,
                    ),
                    GestureDetector(
                      onTap: () {
                        _count = (int.parse(_count) + 1).toString();
                        _reloadPrice();

                        // setState(() {
                        //   _count = (int.parse(_count) + 1).toString();
                        //   _outPrice = (double.parse(this.widget.entity.outPrice) * int.parse(_count)).toString();
                        // });
                      },
                      child: Icon(
                        Icons.add_circle,
                        color: Colours.themeColor,
                        size: 24,
                      ),
                    ),
                    SizedBox(
                      width: 8,
                    ),
                  ],
                ),
                // WidgetUtils.itmeStyleView('购买数量', '1',
                //     contentAlignment: Alignment.centerRight),
              ),
              Container(
                  margin: EdgeInsets.only(top: 10, bottom: 10),
                  child: Column(
                    children: widget.entity.lstCommoOptsModels
                        .map((LzCommoOptsModel e) {
                      return LzProductSelectSkuWidget(
                        e,
                        clickCallBack: () {
                          _reloadPrice();
                        },
                      );
                    }).toList(),
                  )),
              Container(
                padding: EdgeInsets.all(16),
                color: Colours.title_white,
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        "${this.widget.entity.giftRemark}",
                        style: TextStyle(color: Colours.text_2222),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: _bottomView(),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.only(top: 4),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                // RouteUtil.closeView();
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    WidgetUtils.getTextColorView(
                        '实付款：', Colors.white, Dimens.FONT_SIZE_16,
                        fontweight: FontWeight.w500),
                    WidgetUtils.getTextColorView(
                        Utils.formatNum(num.parse(_outPrice), 2),
                        Colours.themeColor,
                        Dimens.FONT_SIZE_16,
                        fontweight: FontWeight.w500),
                  ],
                ),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.blackground_black_239,
                ),
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: GestureDetector(
              onTap: () {
                if (ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)) {
                  BotToast.showText(text: '请添加收货地址');
                  return;
                }
                Map<String, dynamic> data = {};
                Map<String, dynamic> entityJson = this.widget.entity.toJson();
                data["lstCommoOpts"] = entityJson["lstCommoOpts"];
                data['userId'] = BaseConstant.userId;
                data['commoSpecId'] = this.widget.entity.id;
                data['realPrice'] = this.widget.entity.outPrice;
                data['shopCt'] = _count;
                _bloc.validateDate.add(data);
              },
              child: Container(
                alignment: FractionalOffset.center,
                height: 54,
                child: WidgetUtils.getTextColorView(
                    '去支付', Colors.white, Dimens.FONT_SIZE_16,
                    fontweight: FontWeight.w500),
                decoration: BoxDecoration(
                  // borderRadius: BorderRadius.circular(10),
                  color: Colours.text_9C1,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _shoppingView() {
    return Container(
      decoration: BoxDecoration(
        color: Colours.title_white,
      ),
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: 110.0,
              width: 110.0,
              child: FadeInImage.assetNetwork(
                image: this.widget.entity.imgUrl,
                placeholder: 'images/picture_loading.png' /* 指定gif */,
                fit: BoxFit.contain,
              ),
            ),
            flex: 2,
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  WidgetUtils.getTextColorView(
                    this.widget.entity.name,
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  WidgetUtils.getTextColorView(
                    '生鲜产品不支持拒收，如有破损联系客服秒赔付',
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                  SizedBox(
                    height: Dimens.FONT_SIZE_16,
                  ),
                  WidgetUtils.getTextColorView(
                    '¥ ${this.widget.entity.outPrice}/件',
                    Colours.text_2222,
                    Dimens.FONT_SIZE_14,
                  ),
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }

  Widget _showAddressView() {
    return StreamBuilder(
      stream: _addressBloc.sendinitData,
      initialData: BaseConstant.adressEntity,
      builder: (BuildContext contexts, AsyncSnapshot<Object> snapshot) {
        Object object = snapshot.data;
        if (object is List) {
          _listEntity = object;
        }
        int count = _listEntity.length;
        if (count > 0) {
          BaseConstant.adressEntity = _listEntity[0];
        }
        return _addressView();
      },
    );
  }

  Widget _addressView() {
    return GestureDetector(
      onTap: () {
        if (ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)) {
          RouteUtil.goParameter(AddAdressPage(
            action: '新增地址',
          ));
        } else {
          RouteUtil.goParameter(MyAdressPage(
            type: BaseConstant.SELECT_ADRESS,
          ));
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colours.title_white,
        ),
        child: Row(
          children: <Widget>[
            Expanded(
                child: ObjectUtil.isEmptyString(BaseConstant.adressEntity.id)
                    ? Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 16, horizontal: 8),
                        decoration: BoxDecoration(
                          color: Colours.title_white,
                        ),
                        alignment: Alignment.centerLeft,
                        child: WidgetUtils.getTextColorView(
                          '请添加收货地址',
                          Colours.text_2222,
                          Dimens.FONT_SIZE_18,
                        ),
                      )
                    : Container(
                        alignment: Alignment.centerLeft,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 8, vertical: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                WidgetUtils.getTextColorView(
                                  Utils.reTextNull(
                                      BaseConstant.adressEntity.souJianRenName),
                                  Colours.text_2222,
                                  Dimens.FONT_SIZE_18,
                                ),
                                SizedBox(
                                  width: 32,
                                ),
                                WidgetUtils.getTextColorView(
                                  Utils.reTextNull(BaseConstant
                                      .adressEntity.souJianRenPhone),
                                  Colours.text_2222,
                                  Dimens.FONT_SIZE_18,
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 16,
                            ),
                            WidgetUtils.getTextColorView(
                              Utils.reTextNull(_cityAddrss()),
                              Colours.text_2222,
                              Dimens.FONT_SIZE_16,
                            ),
                          ],
                        ),
                      )),
            Icon(
              Icons.keyboard_arrow_right,
              color: Colours.themeColor,
              size: 32,
            ),
          ],
        ),
      ),
    );
  }

  String _cityAddrss() {
    if (ObjectUtil.isEmptyString(
        BaseConstant.adressEntity.souJianRenProvName)) {
      return '';
    }
    StringBuffer stringBuffer = StringBuffer();
    if (BaseConstant.adressEntity.souJianRenProvName ==
        BaseConstant.adressEntity.souJianRenCityName) {
      stringBuffer
        ..write(BaseConstant.adressEntity.souJianRenCityName)
        ..write(BaseConstant.adressEntity.souJianRenTownName)
        ..write(BaseConstant.adressEntity.souJianRenAddress);
    } else {
      stringBuffer
        ..write(BaseConstant.adressEntity.souJianRenProvName)
        ..write(BaseConstant.adressEntity.souJianRenCityName)
        ..write(BaseConstant.adressEntity.souJianRenTownName)
        ..write(BaseConstant.adressEntity.souJianRenAddress);
    }
    return stringBuffer.toString();
  }

  @override
  void dispose() {
    _selectSubscription?.cancel();
    _validateSubscription?.cancel();
    _addSubscription?.cancel();
    _calculSubscription.cancel();
    super.dispose();
  }
}

//选择SkuList
class LzProductSelectSkuWidget extends StatefulWidget {
  final LzCommoOptsModel optsModel;
  final Function() clickCallBack;
  LzProductSelectSkuWidget(this.optsModel, {Key key, this.clickCallBack})
      : super(key: key);

  @override
  _LzProductSelectSkuWidgetState createState() =>
      _LzProductSelectSkuWidgetState();
}

class _LzProductSelectSkuWidgetState extends State<LzProductSelectSkuWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      alignment: Alignment.topLeft,
      padding: EdgeInsets.all(8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            child: LzText(widget.optsModel.optsName,
                color: Colors.black, fontSize: 18),
          ),
          Container(
            padding: EdgeInsets.only(left: 30, top: 10),
            child: Wrap(
              // 扩展方式，横向堆砌
              direction: Axis.horizontal,
              // 对齐方式
              alignment: WrapAlignment.start,
              // 主轴空隙间距
              spacing: 10,
              // run的对齐方式
              runAlignment: WrapAlignment.start,
              // run空隙间距
              runSpacing: 10,
              // 交叉轴对齐方式
              crossAxisAlignment: WrapCrossAlignment.start,
              // 文本对齐方向
              textDirection: TextDirection.ltr,
              // 确定垂直放置子元素的顺序，以及如何在垂直方向上解释开始和结束。 默认down
              verticalDirection: VerticalDirection.down,

              // alignment: WrapAlignment.start,
              // runAlignment: WrapAlignment.start,
              children: widget.optsModel.lstCommoOpt.map((LstCommoOpt e) {
                bool isBeSel = e.beSel == "Y";
                return GestureDetector(
                  onTap: () {
                    if (widget.optsModel.beSingleSel == "Y") {
                      if (e.beSel == "Y") {
                        e.beSel = "N";
                      } else {
                        //如果是单选的. 把之前选择的重置
                        widget.optsModel.lstCommoOpt.forEach((element) {
                          element.beSel = "N";
                        });
                        //点击之后取反
                        e.beSel = e.beSel == "N" ? "Y" : "N";
                      }
                    } else {
                      //点击之后取反
                      e.beSel = e.beSel == "N" ? "Y" : "N";
                    }

                    if (widget.clickCallBack() != null) {
                      widget.clickCallBack();
                    }
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    decoration: BoxDecoration(
                        border: Border.all(
                            color: isBeSel ? Colours.login_orgen : Colors.black,
                            width: 1),
                        borderRadius: BorderRadius.circular(5),
                        color: isBeSel
                            ? Colours.login_orgen
                            : Colours.title_white),
                    child: LzText("${e.optName}",
                        color: isBeSel ? Colors.white : Colors.black),
                  ),
                );
              }).toList(),
            ),
          )
        ],
      ),
    );
  }
}
